#!/srv/newsblur/venv/newsblur3/bin/python

import json
import os
import urllib

import urllib2

from vendor.munin import MuninPlugin


class HookboxPlugin(MuninPlugin):
    title = 'hookbox'
    args = "--base 1000"
    vlabel = "Y"
    info = "Subscibed users"
    scale = False

    def get_channels(self):
        return os.environ.get('HOOKBOX_CHANNELS', '').split(',')

    def get_url(self):
        return os.environ.get('HOOKBOX_URL', 'http://localhost:8001/rest')

    def get_secret(self):
        return os.environ.get('HOOKBOX_SECRET', '')


    @property
    def fields(self):
        return (
            (channel, dict(
                label=channel,
                info="%s - users" % channel,
                type="GAUGE",
            ))
            for channel in self.get_channels()
        )

    def get_channel_info(self, channel_name):
        values = {
            'channel_name': channel_name,
            'secret': self.get_secret(),
        }
        req = urllib2.Request("%s/get_channel_info?%s" % (self.get_url(), urllib.urlencode(values)))
        resp = urllib2.urlopen(req)
        return json.loads(resp.read())

    def get_subscribers(self, channel_name):
        try:
            return len(self.get_channel_info(channel_name)[1]['subscribers'])
        except (urllib2.URLError, KeyError), e:
            return 'U'

    def execute(self):
        return dict(
            (channel_name, self.get_subscribers(channel_name))
            for channel_name in self.get_channels()
        )

if __name__ == "__main__":
    HookboxPlugin().run()
